package com.src.hb;

import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import com.src.hb.model.Timer;

public class TimersExecutor {
	/**
	 * Kolejka Timerów do wykonania
	 */
	private Queue<Timer> queue = new LinkedBlockingQueue<Timer>();
	private boolean isExecutorActive = false;
	private Executor executor = Executors.newFixedThreadPool(4, new ThreadsFactory());

	/**
	 * Wykonaj zadanie Timera. Właściwie, to dodaje zadanie timera do kolejki.
	 * 
	 * @param timer
	 */
	public synchronized void execute(Timer timer) {
		queue.add(timer);
		if (!isExecutorActive) {
			consumeQueue();
		}
	};

	/**
	 * Konsumowanie timerów z kolejki.
	 */
	private synchronized void consumeQueue() {
		if (!isExecutorActive) {
			if (queue.size() > 0) {
				isExecutorActive = true;
				while (!queue.isEmpty()) {
					Timer t = queue.poll();
					if (!consumeTimer(t)
							&& t.getFailedAttempts() >= Timer.MAX_COUNT_TRY) {
						queue.add(t);
					}
				}
				isExecutorActive = false;
			}
		}
	}

	private boolean consumeTimer(final Timer timer) {
		Runnable object = new Runnable() {
			
			public void run() {
				System.out.println(timer.getTm_name() + ": "+timer.getTm_id());	
			}
		};
		executor.execute(object);
		return true;
	}

}
